from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

from rango.forms import UserForm, UserProfileForm
from django.contrib.auth import authenticate, login, logout
from rango.utils.general import get_back_link

from django.contrib.auth.decorators import login_required
from rango.view.category import get_category_list

def register(request):
    context = RequestContext(request)
    registered = False
    
    if request.method == "POST":
        user_form = UserForm(data = request.POST)
        profile_form = UserProfileForm(data = request.POST)
        
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            
            user.set_password(user.password)
            user.save()
            
            profile = profile_form.save(commit=False)
            profile.user = user
            
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
            
            profile.save()
            
            registered = True
        else:
            print user_form.errors, profile_form.errors
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
        
    return render_to_response(
            'rango/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered,
            'cat_list': get_category_list()}, context)
            
def user_login(request):
    context = RequestContext(request)
    
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        
        user = authenticate(username=username, password=password)
        
        if user:
            if user.is_active:
                login(request, user)
                next = request.POST['next']
                if not next:
                   next = '/rango/' 
                return HttpResponseRedirect(next)
            else:
                return HttpResponse("Your Rango account is disabled")
        else:
            print "Invalid login details: {0}, {1}".format(username, password)
            return HttpResponse("Invalid login details supplied.<br/><a href='/rango/login/'>Try again</a>")
    else:
        return render_to_response('rango/login.html', {'next':request.GET.get('next', get_back_link(request)),'cat_list': get_category_list()}, context)

@login_required
def user_logout(request):
    logout(request)

    return HttpResponseRedirect('/rango/')